package cn.yanhu.kuwanapp.my.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import cn.woochen.comlib.BaseActivity
import cn.woochen.comlib.util.OnSingleClickListener
import cn.woochen.comlib.util.ext.setOnSingleClickListener
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.databinding.ActivityEditNicknameBinding
import cn.yanhu.kuwanapp.user.UserViewModel
import cn.yanhu.kuwanapp.utils.ext.parseState
import cn.yanhu.kuwanapp.widgets.TitleView
import com.jakewharton.rxbinding4.widget.textChanges

/**
 * 类描述：修改昵称
 * @author：woochen
 * create at：2021/8/6 11:16 PM
 */
class EditNicknameActivity : BaseActivity<ActivityEditNicknameBinding, UserViewModel>(),
    OnSingleClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView()
    }

    override fun setContentView(): Int = R.layout.activity_edit_nickname

    override fun initData() {
        setStatusBarStyle(false)
        mBinding.etNickname.setText(mNickName)
    }

    override fun registerNecessaryObserver() {
        super.registerNecessaryObserver()
        //更新用户信息
        mViewModel.editUserInfoInfo.observe(this, Observer {
            parseState(it,{
                back()
            })
        })
    }

    override fun initListener() {
        mBinding.titleView.titleListner =  object : TitleView.OnTitleClickListener {
            override fun leftClick() {
                back()
            }

            override fun rightClick() {
                val trim = mBinding.etNickname.text.toString().trim()
                if (mNickName != trim){
                    mViewModel.editUserInfo("",trim)
                }else{
                    back()
                }
            }
        }
        mBinding.etNickname.textChanges().subscribe {
            mBinding.ivClear.isVisible = it.isNotBlank()
        }
        mBinding.ivClear.setOnSingleClickListener(this)
    }

    private val mNickName by lazy {
        intent.getStringExtra(EXTRA_NICKNAME)
    }

    companion object {
        private const val EXTRA_NICKNAME = "extra_nickname"
        fun start(context: Context, nickName: String) {
            val intent = Intent(context, EditNicknameActivity::class.java)
            intent.putExtra(EXTRA_NICKNAME, nickName)
            context.startActivity(intent)
        }
    }

    override fun onSingleClick(v: View?) {
        when (v) {
            mBinding.ivClear -> {//清除文本
                mBinding.etNickname.setText("")
            }
            else -> {
            }
        }
    }
}